from typing import List
from sqlalchemy.exc import IntegrityError
from sqlalchemy import desc
from ..models.favorite_path import FavoritePath
from ..infrastructure.database import SessionLocal
import logging
import os

logger = logging.getLogger(__name__)

class FavoritePathManager:
    def get_all(self) -> List[FavoritePath]:
        """获取所有常用路径"""
        with SessionLocal() as session:
            return session.query(FavoritePath).order_by(desc(FavoritePath.create_time)).all()

    def add(self, path: str, name: str) -> FavoritePath:
        """添加新的常用路径"""
        with SessionLocal() as session:
            try:
                # 检查是否已存在相同路径
                existing = session.query(FavoritePath).filter(
                    FavoritePath.path == path
                ).first()
                if existing:
                    raise IntegrityError(
                        "Duplicate path", 
                        params={"path": path}, 
                        orig=None
                    )
                
                # 创建新记录
                favorite_path = FavoritePath(
                    path=path,
                    name=name
                )
                session.add(favorite_path)
                session.commit()
                session.refresh(favorite_path)
                
                logger.info(f"Added new favorite path: {path} ({name})")
                return favorite_path
                
            except IntegrityError:
                session.rollback()
                logger.error(f"Path already exists: {path}")
                raise
            except Exception as e:
                session.rollback()
                logger.error(f"Error adding favorite path: {str(e)}")
                raise

    def delete(self, path_id: int) -> bool:
        """删除指定的常用路径"""
        with SessionLocal() as session:
            try:
                result = session.query(FavoritePath).filter(
                    FavoritePath.id == path_id
                ).delete()
                session.commit()
                return result > 0
            except Exception as e:
                session.rollback()
                logger.error(f"Error deleting favorite path: {str(e)}")
                raise

    def init_default_paths(self) -> List[FavoritePath]:
        """初始化默认路径"""
        default_paths = [
            ("H:\\Download", "下载目录"),
            ("H:\\Documents", "文档"),
            ("H:\\Pictures", "图片"),
            ("H:\\Videos", "视频")
        ]
        
        added_paths = []
        with SessionLocal() as session:
            for path, name in default_paths:
                try:
                    # 检查路径是否存在且未被添加
                    if os.path.exists(path) and not session.query(FavoritePath).filter(
                        FavoritePath.path == path
                    ).first():
                        favorite_path = FavoritePath(path=path, name=name)
                        session.add(favorite_path)
                        session.commit()
                        session.refresh(favorite_path)
                        added_paths.append(favorite_path)
                except IntegrityError:
                    session.rollback()
                    continue
                except Exception as e:
                    session.rollback()
                    logger.error(f"Error adding default path: {str(e)}")
                    continue
                    
        return added_paths